<?php

namespace App\Http\Controllers\Admin;


use App\Models\Feedback;
use App\Models\UserInfo;
use App\Validate\FeedbackValidate;
use Illuminate\Support\Facades\DB;

/**
 * 用户留言管理
 */
class FeedbackController extends CommonController
{
    public $model = null;
    public $validate = null;

    public function __construct()
    {
        parent::__construct();

        $this->model = new Feedback();
        $this->validate = new FeedbackValidate();
    }


    /**
     * 用户留言列表
     * @param page 页数    默认第一页
     * @param limit 限制条数   默认 10 条
     * @param type  0 或空，表示全部   1 已回复  2 未回复 
     * @param start_time   开始时间
     * @param end_time   结束时间
     * @param keywords  筛选内容
     */
    public function lists()
    {
        $keywords = $this->request->input('keywords', '');
        $start_time = $this->request->input('start_time', '');
        $end_time = $this->request->input('end_time', '');
        $limit = $this->request->input('limit', '10');
        $page = $this->request->input('page', 1);
        $type = $this->request->input('type', 1);

        $res = $this->model->lists($type, $keywords, $start_time, $end_time, $limit);


        if ($res['total'] == 0 || !$res['data']) {
            return $this->returnApi(203, "暂无数据");
        }

        $res = $this->disPageData($res);
        $res['data'] = $this->addSerialNumber($res['data'], $page, $limit);

        return $this->returnApi(200, "查询成功", true, $res);
    }

    /**
     * 回复用户留言（只能回复一次）
     * @param id 留言id
     * @param content 回复内容
     */
    public function reply()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('reply')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        DB::beginTransaction();
        try {
            $res = $this->model->reply($this->request->id, $this->request->content);

            //写入系统消息
            if ($res->user_id) {
                $userInfoObj = new UserInfo();
                $account_id = $userInfoObj->getAccountId($res->user_id);
                $this->systemAdd('意见反馈回复', $res->user_id, $account_id, 2, $res->id, $this->request->content);
            }

            DB::commit();
            return $this->returnApi(200, "回复成功");
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, "回复失败");
        }
    }
}
